#include "libraryfilter.h"

#include <QtCore/qdebug.h>

LibraryFilter::LibraryFilter(Mode mode, QWidget *parent) :
    QComboBox(parent)
{
    m_mode = mode;
    init();
}

void LibraryFilter::addCategory(const QString &category)
{
    if (count() == 1)
        addItem(category);
    else if (count() == 2)
    {
        if (category < itemText(1))
            insertItem(1, category);
        else
            addItem(category);
    }
    else
    {
        bool added = false;
        for (int i = 1; (i < count() - 1) && !added; ++i)
        {
            const QString currText = itemText(i);
            const QString nextText = itemText(i + 1);
            qDebug() << category << currText << nextText
                     << category.localeAwareCompare(currText)
                     << category.localeAwareCompare(nextText);
            if (category.localeAwareCompare(currText) < 0)
            {
                insertItem(i, category);
                added = true;
            }
            else if (category.localeAwareCompare(currText) > 0 &&
                     category.localeAwareCompare(nextText) < 0)
            {
                insertItem(i + 1, category);
                added = true;
            }
        }
        if (!added)
            addItem(category);
    }
}

void LibraryFilter::init()
{
    clear();
    switch (m_mode)
    {
    case LibraryMode:
        addItem(tr("<All Libraries>"));
        break;
    case GroupMode:
        addItem(tr("<All Groups>"));
        break;
    case ReferenceMode:
        addItem(tr("<All References>"));
        break;
    }
}

void LibraryFilter::removeCategory(const QString &category)
{
    for (int i = 1; i < count(); ++i)
        if (itemText(i) == category)
        {
            removeItem(i);
            break;
        }
}
